import ProductAPI from '@/api/Product';
import { mapField, ModalSelectTable, useCall, useTableColumns } from '@/components';
import { PRODUCT_TYPE_INSURE } from '@/constants/options';
import { CompanySelectField } from '@/pages/components';
import { enumToOptions, simpleMerge } from '@/utils';
import React, { forwardRef, useMemo } from 'react';

const FIELDS = [
  ['productCode', '险种编码'],
  ['productName', '险种名称'],
  ['productCategory', '险种分类', 'dict', { code: 'agency', hides: [''], allowClear: true }],
  ['productType', '主附险类型', 'select', { options: enumToOptions(PRODUCT_TYPE_INSURE), allowClear: true }],
].map(mapField);

const COLUMNS = [
  { dataIndex: 'productCode', title: '险种编码', width: 140 },
  { dataIndex: 'companyName', title: '保险公司', width: 110, ellipsis: true },
  { dataIndex: 'productName', title: '险种名称' },
  { dataIndex: 'productCategory', title: '险种分类', dict: 'agency', width: 80 },
  { dataIndex: 'productType', title: '主附险类型', map: PRODUCT_TYPE_INSURE, width: 120 },
];

SelectProduct = forwardRef(SelectProduct);

function SelectProduct({ companyCode, notProposal, notCompare, ...props }, ref) {
  const onService = useCall((...args) => {
    const ret = props.onService?.(...args) || [args[0]];
    return simpleMerge([{ companyCode, notProposal, notCompare }], ret);
  });

  const onResult = useCall((result) => result?.data ?? []);

  const fields = useMemo(
    () => [...FIELDS, !companyCode && mapField(['companyCode', '保险公司', CompanySelectField])].filter(Boolean),
    [companyCode],
  );

  return (
    <ModalSelectTable
      title='选择险种'
      ref={ref}
      {...props}
      service={ProductAPI.selectAll}
      onService={onService}
      fields={fields}
      columns={useTableColumns(COLUMNS)}
      onResult={onResult}
    />
  );
}

export default SelectProduct;
